package com.ruoyi.auth.service;

import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteEmailService;
import com.ruoyi.system.api.RemoteSmsService;
import com.ruoyi.system.api.RemoteTenantService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.RegisterInfo;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteTenantService remoteTenantService;

    @Autowired
    private RemoteEmailService remoteEmailService;
    @Autowired
    private RemoteSmsService remoteSmsService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写", SecurityConstants.IGNORE_APPLICATION_CODE);
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围", SecurityConstants.IGNORE_APPLICATION_CODE);
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围", SecurityConstants.IGNORE_APPLICATION_CODE);
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单", SecurityConstants.IGNORE_APPLICATION_CODE);
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在", userResult.getData().getSysUser().getEnterpriseCode());
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除", userResult.getData().getSysUser().getEnterpriseCode());
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员", userResult.getData().getSysUser().getEnterpriseCode());
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功", userResult.getData().getSysUser().getEnterpriseCode());
        return userInfo;
    }

    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功", SecurityUtils.getEnterpriseCode());
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功", SecurityConstants.IGNORE_APPLICATION_CODE);
    }

    public R<String> registerTenantInfo(RegisterInfo registeinfo) {
        // 注册租户信息
        R<String> r =  remoteTenantService.registerTenantInfo(registeinfo, SecurityConstants.INNER);
        if(R.SUCCESS != r.getCode())
            throw new ServiceException(r.getMsg());
        return r;
    }

    /**
     * 混合模式登录：手机号或邮箱，每种又分密码模式、验证码模式
     * @param form
     * @return
     */
    public LoginUser loginMixed(LoginBody form) {
        //手机号和邮箱不能同时为空，同时为不空
        if(StringUtils.isEmpty(form.getMobile()) && StringUtils.isEmpty(form.getMail()))
            throw new ServiceException("手机号和邮箱不能同时为空");
        if(!StringUtils.isEmpty(form.getMobile()) && !StringUtils.isEmpty(form.getMail()))
            throw new ServiceException("手机号和邮箱不能同时为非空");

        //手机号登录
        if (!StringUtils.isEmpty(form.getMobile())){
            R<LoginUser> userResult = remoteUserService.getByMobile(form.getMobile(), SecurityConstants.INNER);
            SysUser user = verifyUserResult(userResult,form.getMobile());

            if(LoginBody.MODE_PASSWORD.equals(form.getVerifyMode())){
                passwordService.validate(user, form.getCodeOrPassword());
            }else{
                R<Boolean> checkResult = remoteSmsService.verifyCode(form.getMobile(), form.getCodeOrPassword());
                if(R.FAIL == checkResult.getCode()) {
                    recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, checkResult.getMsg(),user.getEnterpriseCode());
                    throw new ServiceException(checkResult.getMsg());
                }

                if(!checkResult.getData()) {
                    recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "验证码错误!", user.getEnterpriseCode());
                    throw new ServiceException("验证码错误");
                }
            }
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "您已登录本系统!", user.getEnterpriseCode());
            return userResult.getData();
        }else{
            R<LoginUser> userResult = remoteUserService.getByMail(form.getMail(), SecurityConstants.INNER);
            SysUser user = verifyUserResult(userResult,form.getMail());
            if(LoginBody.MODE_PASSWORD.equals(form.getVerifyMode())){
                passwordService.validate(user, form.getCodeOrPassword());
            }else{
                R<Boolean> checkResult = remoteEmailService.verifyCode(form.getMail(),form.getCodeOrPassword());
                if(R.FAIL == checkResult.getCode()) {
                    recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, checkResult.getMsg(), user.getEnterpriseCode());
                    throw new ServiceException(checkResult.getMsg());
                }
                if(!checkResult.getData()) {
                    recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "验证码错误!", user.getEnterpriseCode());
                    throw new ServiceException("验证码错误");
                }
            }
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "您已登录本系统!", user.getEnterpriseCode());
            return userResult.getData();
        }
    }

    private SysUser verifyUserResult(R<LoginUser> userResult, String key) {
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(key, Constants.LOGIN_FAIL, "登录用户不存在", SecurityConstants.IGNORE_APPLICATION_CODE);
            throw new ServiceException("登录用户：" + key + " 不存在");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        //设置当前企业编码，以便后续记录
        SecurityContextHolder.setEnterpriseCode(user.getEnterpriseCode());
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(key, Constants.LOGIN_FAIL, "对不起，您的账号已被删除", user.getEnterpriseCode());
            throw new ServiceException("对不起，您的账号：" + key + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(key, Constants.LOGIN_FAIL, "用户已停用，请联系管理员", user.getEnterpriseCode());
            throw new ServiceException("对不起，您的账号：" + key + " 已停用");
        }
        return user;
    }
}
